package com.gz.mylife.im;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import net.tsz.afinal.FinalDb;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.account.po.UserInfo;
import com.zl.smartmall.library.util.CrashHandler;

import android.content.Context;
import android.text.TextUtils;


/**
 * 私信聊天内容列表
 * @author linwenming
 *
 */
public class MessageDao{

	private static final String TAG = "Message";
	
	//String where ="id NOT IN(SELECT ID FROM tb_message where pmid="+pmid+" ORDER BY dateline DESC limit 0,50)";
	// 3 * 24 * 60 * 60 * 1000 3天
	
	/**
	 * ten minutes; least unit seconds
	 */
	private static final long SHOW_TIME_POINT = 10 * 60;
	
	
	/**
	 * 保存前清除老数据
	 * 1、首次加载的时候保存
	 * 2、用户主动刷新保存
	 * 3、jpush 消息保存
	 * @param cxt
	 * @param messages
	 */
	public static void save(Context cxt,List<IMessage> messages){
		FinalDb finalDb = FinalDb.create(cxt);
		if(messages != null && messages.size()>0){
			finalDb.deleteByWhere(IMessage.class, "pmid="+messages.get(0).getPmid()+" and "+"currentUID="+IAuth.getInstance().loadUserInfo().getUid());
			finalDb.batchSave(messages);
		}
	}
	public static void save2(Context cxt,List<IMessage> messages){
		FinalDb finalDb = FinalDb.create(cxt);
		finalDb.batchSave(messages);
	}
	/**
	 * 保存没有重复的数据，同时去重内存中的重复数据
	 * @param cxt
	 * @param messages
	 */
	public static void saveNoRepeat(Context cxt,List<IMessage> messages){
		if(messages == null || messages.size() == 0){
			return;
		}
		List<IMessage> list = new ArrayList<IMessage>();
		
		FinalDb finalDb = FinalDb.create(cxt);
		for(int i = 0;i<messages.size();i++){
			IMessage msg = messages.get(i);
			String where =String.format("pmid=%d and lastid=%d and currentUID=%d",msg.getPmid(),msg.getLastid(),IAuth.getInstance().loadUserInfo().getUid());
			int count = finalDb.getCount(IMessage.class, where);
			if(count == 0){
				finalDb.save(msg);
			}else{
				list.add(msg);
			}
		}
		for(int i = 0;i<list.size();i++){
			messages.remove(list.get(i));
		}
		
	}
	public static void saveNoRepeat(Context cxt,IMessage message){
		if(message == null){
			return;
		}
		FinalDb finalDb = FinalDb.create(cxt);
		String where =String.format("pmid=%d and lastid=%d and currentUID=%d",message.getPmid(),message.getLastid(),IAuth.getInstance().loadUserInfo().getUid());
		int count = finalDb.getCount(IMessage.class, where);
		if(count == 0){
			finalDb.save(message);
		}
	}
	public static void reSetMsgIsConnect(Context cxt,IMessage msg){
		if(msg == null){
			return;
		}
		FinalDb finalDb = FinalDb.create(cxt);
		String where =String.format("pmid=%d and msgId=%d and currentUID=%d",msg.getPmid(),msg.getMsgId(),IAuth.getInstance().loadUserInfo().getUid());
		msg.setIsConnect(0);
		finalDb.update(msg, where);
	}
	
	public static void save(Context cxt,IMessage message){
		if(message == null)
			return;
		String where =String.format("pmid=%d and lastid=%d and currentUID=%d",message.getPmid(),message.getLastid(),IAuth.getInstance().loadUserInfo().getUid());
		FinalDb finalDb = FinalDb.create(cxt);
		finalDb.deleteByWhere(IMessage.class, where);
		finalDb.save(message);
	}
	/**
	 * 判断发送的消息是否联系，当收到的消息比本地最大消息id小时丢弃这条消息（获取缺少消息的请求中回重新请求这条数据）
	 * 
	 * @param cxt
	 * @param message
	 * @return  -1  表示消息可以丢弃，不要显示通知和发送通知到观察者
	 */
	public static int judgeIsConnection(Context cxt,IMessage message){
		if(message == null){
			return 1;
		}
		int maxId = getMaxMsgId(cxt, message.getPmid());
		if(maxId == 0){//本地无数据
			save(cxt, message);
		}else{
			if(message.getMsgId() - maxId ==1){//连续的消息
				save(cxt, message);
			}else if(message.getMsgId() - maxId >1){//非连续的消息
				message.setIsConnect(1);
				message.setMaxMsgId(maxId);
				save(cxt, message);
			}else{
				//去重保存(这里按飞哥的就是小于不保存，因为后面回去重新请求)
				//saveNoRepeat(cxt, message);
				return -1;
			}
		}
		return 0;
		
	}
	public static int getMaxMsgId(Context cxt,int pmid){
		FinalDb finalDb = FinalDb.create(cxt);
	    List<IMessage> messages = finalDb.findAllByWhere(IMessage.class, "pmid="+pmid+" and currentUID="+IAuth.getInstance().loadUserInfo().getUid()+" order by msgid desc limit "+1);
	    if(messages != null &&messages.size()>0){
	    	return messages.get(0).getMsgId();
	    }
	    return 0;
	}
	public static IMessage findMessage(Context cxt,IMessage message){
		String where =String.format("pmid=%d and lastid=%d",message.getPmid(),message.getLastid());
		FinalDb finalDb = FinalDb.create(cxt);
		return finalDb.getUnique(IMessage.class, where);
	}
	
	/**
	 * 删除之前的断层的老数据
	 * @param cxt
	 * @param id
	 */
	public static void deleteDiscardByLastId(Context cxt,int lastid){
		FinalDb finalDb = FinalDb.create(cxt);
		finalDb.deleteByWhere(IMessage.class, "lastid <"+lastid);
	}
	
	public static IMessage adapter4jpush(JSONObject data){
		CrashHandler.d(TAG, "jpush:"+data.toString());
		IMessage message = null;
		try{
			message = new IMessage();
			message.setLastid(data.getInt("l"));
			message.setPmid(data.getInt("m"));
			message.setToUid(IAuth.getInstance().loadUserInfo().getUid());  // 发给我的消息
			message.setFromUid(data.getInt("u"));
			message.setDateline(data.getLong("d"));
			message.setContent(data.getString("c"));
			message.setPicture(data.getString("p"));
			message.setWidth(data.getInt("pw"));
			message.setHeight(data.getInt("ph"));
			message.setMyType(data.getInt("mtype"));
			if(TextUtils.isEmpty(message.getPicture())){
				message.setShowType(IMessage.TYPE_TEXT);
			} else {
				message.setShowType(IMessage.TYPE_PHOTO);
			}
			if(data.getInt("mtype") == 1){
				message.setDiscuzId(data.getInt("discuz_id"));
				message.setTopicId(data.getInt("topic_id"));
			}
			if(data.getInt("mtype") == 2){
				message.setDiscuzId(data.getInt("discuz_id"));
				message.setTopicId(data.getInt("topic_id"));
				message.setTieUrl(data.getString("url"));
			}
			message.setMsgId(data.getInt("i"));
			message.setGender(data.getInt("g"));
			message.setCurrentUID(IAuth.getInstance().loadUserInfo().getUid());
			
			
		}catch(JSONException e){
			e.printStackTrace();
		}
		return message;
	}
	
	public static IMessage adapter(JSONObject data){
		IMessage bean = null;
		try{
			bean = new IMessage();
			bean.setLastid(data.getInt("lastid"));
			bean.setPmid(data.getInt("pmid"));
			bean.setFromUid(data.getInt("uid"));
			bean.setToUid(data.getInt("fuid"));
			bean.setContent(data.getString("content"));
			bean.setDateline(data.getLong("dateline"));
			bean.setPicture(data.getString("picture"));
			bean.setPicture_thumb(data.getString("picture_thumb"));
			bean.setWidth(data.getInt("width"));
			bean.setHeight(data.getInt("height"));
			bean.setShowType(data.getInt("type"));
			bean.setMyType(data.getInt("mtype"));
			bean.setMsgId(data.getInt("msgid"));
			bean.setCurrentUID(IAuth.getInstance().loadUserInfo().getUid());
			
			if(data.getInt("mtype") == 1){
				JSONObject extendJson = data.getJSONObject("extends");
				bean.setDiscuzId(extendJson.getInt("discuz_id"));
				bean.setTopicId(extendJson.getInt("topic_id"));
			}
			if(data.getInt("mtype") == 2){
				JSONObject extendJson = data.getJSONObject("extends");
				bean.setDiscuzId(extendJson.getInt("discuz_id"));
				bean.setTopicId(extendJson.getInt("topic_id"));
				bean.setTieUrl(extendJson.getString("url"));
			}
		}catch(JSONException e){
			e.printStackTrace();
		}
		return bean;
	}
	
	
	public static List<IMessage> adapter(JSONArray array){
		UserInfo userinfo = IAuth.getInstance().loadUserInfo();
		int len = array.length();
		List<IMessage> beans = new ArrayList<IMessage>(len);
		for (int i=0;i<len;i++) {
			try {
				IMessage bean =adapter(array.getJSONObject(i));
				if(userinfo != null && bean.getFromUid() == userinfo.getUid()){
					bean.setComMsg(true);
				} else {
					bean.setComMsg(false);
				}
				beans.add(bean);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return beans;
	}
	
	static class MyComparator implements Comparator<IMessage> {
		@Override
		public int compare(IMessage bean1,IMessage bean2) {
			// 降序
			if (bean1.getDateline() > bean2.getDateline()) {
				return 1;
			} else if (bean1.getDateline() == bean2.getDateline()) {
				return 0;
			} else {
				return -1;
			}
		}
	}
	
	public static List<IMessage> getSessionMsg(Context cxt ,int pmid){
		FinalDb finalDb = FinalDb.create(cxt);
		List<IMessage> messages = finalDb.findAllByWhere(IMessage.class, "pmid="+pmid, "lastid asc");
		filterShowTime(messages);
		return messages;
		
	}
	public static List<IMessage> getSessionMsg(Context cxt ,int pmid,int lastId,int limit){
		FinalDb finalDb = FinalDb.create(cxt);
		List<IMessage> messages;
		if(lastId == -1){
		    messages = finalDb.findAllByWhere(IMessage.class, "pmid="+pmid+" order by lastid desc limit "+limit);
			
		}else{
			messages = finalDb.findAllByWhere(IMessage.class, "pmid="+pmid+" and lastid<"+lastId+" order by lastid desc limit "+limit);
		}
		if(messages != null){
			for(int i = 0;i<messages.size();i++){
				CrashHandler.d(TAG, "message :"+messages.get(i).toString());
			}
		}else{
			CrashHandler.d(TAG, "message is null");
		}
		filterShowTime(messages);
		return messages;
		
	}
	public static List<IMessage> getSessionMsgById(Context cxt ,int pmid,int id,int limit){
		FinalDb finalDb = FinalDb.create(cxt);
		List<IMessage> messages;
		if(id == -1){
			messages = finalDb.findAllByWhere(IMessage.class, "pmid="+pmid+" and currentUID="+IAuth.getInstance().loadUserInfo().getUid()+" order by id desc limit "+limit);
		}else{
			messages = finalDb.findAllByWhere(IMessage.class, "pmid="+pmid+" and currentUID="+IAuth.getInstance().loadUserInfo().getUid()+" and id<"+id+" order by id desc limit "+limit);
		}
		if(messages != null){
			for(int i = 0;i<messages.size();i++){
				CrashHandler.d(TAG, "message :"+messages.get(i).toString());
				
			}
		}else{
			CrashHandler.d(TAG, "message is null");
		}
		filterShowTime(messages);
		return messages;
		
	}
	
	/**
	 * 计算显示时间
	 * @param beans
	 */
	public static void filterShowTime(List<IMessage> beans) {
		if(beans == null || beans.size() ==0)
			return;
		long timePoint = 0;
		int count = beans.size();
		for (int i = 0; i < count; i++) { 
			IMessage bean = beans.get(i);
			if(timePoint == 0){
				bean.inShowTime = true;
				timePoint = bean.getDateline();
			} else {
				if(bean.getDateline() - timePoint <= SHOW_TIME_POINT){
					bean.inShowTime = false;
				} else {
					bean.inShowTime = true;
					timePoint = bean.getDateline();
				}
			}
		}
	}
	
	public static void filterSingleShowTime(List<IMessage> beans,int index) {
		if(beans == null || beans.size() ==0 || beans.get(index).inShowTime)
			return;
		else if(beans.size() ==1){
			beans.get(index).inShowTime = true;
			return;
		}
		
		IMessage last = beans.get(index);
		
		IMessage pre = null;
		for (int i= index; i>=0; i--) { 
			if(beans.get(i).inShowTime){
				pre = beans.get(i);
				break;
			}
		}
		if(pre == null || last.getDateline() - pre.getDateline() >= SHOW_TIME_POINT){
			last.inShowTime = true;
		}
	}
	
	/**
	 * 丢弃不连接的老数据，暂时跟啊增讨论是每个lastid都是连接的间隔是1
	 * @return 返回不衔接的那条数据的id
	 */
	public static int discardNotConnected(List<IMessage> beans){
		if(beans.size() < 2){
			return 0;
		}
		int result = 0;
		int index = beans.size()-1;
		int preLastid = beans.get(index).getLastid();
		for (int i = index -1; i >= 0; i--) { 
			// 从倒数第二个开始遍历
			System.out.println("preLastid:"+preLastid+" currLastid:"+beans.get(i).getLastid());
			if(preLastid != (beans.get(i).getLastid()+1)){
				result = beans.get(i).getLastid();
				for(int n = i;n>=0;n--){
					beans.remove(n);
				}
				break;
			}
			preLastid = beans.get(i).getLastid();
		}
		return result;
	}
	
	/**
	 * 降序
	 * @param beans
	 * @return
	 */
	public static void sort(List<IMessage> beans){
		Collections.sort(beans, new Comparator<IMessage>(){

			@Override
			public int compare(IMessage arg0, IMessage arg1) {
				
				if(arg0.getId() > arg1.getId()){
					return 1;
				} else if(arg0.getId() == arg1.getId()){
					return 0;
				} else {
					return -1;
				}
			}
		});
	}
	/**
	 * 降序
	 * @param beans
	 * @return
	 */
	public static void sortResponse(List<IMessage> beans){
		Collections.sort(beans, new Comparator<IMessage>(){

			@Override
			public int compare(IMessage arg0, IMessage arg1) {
				
				if(arg0.getMsgId() > arg1.getMsgId()){
					return 1;
				} else if(arg0.getMsgId() == arg1.getMsgId()){
					return 0;
				} else {
					return -1;
				}
			}
		});
	}
	
}
